﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CompanyManageSystem.UI.Info
{
    public partial class Frm_ShowPicture : Form
    {
        #region 属性
        byte[] _data;
        #endregion

        /// <summary>
        /// 构造方法
        /// </summary>
        public Frm_ShowPicture(byte[] data)
        {
            InitializeComponent();
            this._data = data;
        }

        /// <summary>
        /// 窗体加载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Frm_ShowPicture_Load(object sender, EventArgs e)
        {
            pictureEdit1.EditValue = new Bitmap(new MemoryStream(_data));
        }

        /// <summary>
        /// 显示图片
        /// static的好处:调用时直接使用 类.ShowImage() 即可
        /// </summary>
        /// <param name="data"></param>
        public static void ShowImage(byte[] data)
        {
            Frm_ShowPicture frm = new Frm_ShowPicture(data);
            //frm.ChangePhotoSize(data);
            frm.Show();
        }

        public static byte[] ChangePhotoSize(byte[] data)
        {
            int targetWidth = 500;
            //从流中获取字节
            var img = Image.FromStream(new MemoryStream(data));
            if (img.Width > targetWidth || img.Width != img.Height)
            {
                //返回列中的最小值
                var width = new List<int> { targetWidth, img.Width, img.Height }.Min();
                var newimg = new Bitmap(img, new Size(width, width));
                //创建新流
                var ms = new MemoryStream();
                //将图片保存到新流中，并设置格式
                newimg.Save(ms,ImageFormat.Jpeg);
                //将流内容写入字节数组
                return ms.ToArray();
            }
            return data;
        }

    }
}
